package com.service.supply;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.alibaba.excel.EasyExcel;
import com.common.DesUtils;
import com.common.StringUtils;
import com.common.db.RedisUtils;
import com.common.easyui.EasyuiUtils;
import com.common.http.HttpResult;
import com.common.http.HttpStatus;
import com.common.model.Global;
import com.common.model.UserTypeEnum;
import com.common.spring.SpringMvcUtils;
import com.common.utils.MailStmpSend;
import com.dao.supply.CorpDao;
import com.dao.supply.InfoMapper;
import com.dao.supply.LoginMapper;
import com.dao.supply.SupplyBankDao;
import com.dao.supply.UserMapper;
import com.dao.sys.SysUserMapper;
import com.enums.WorkFlowIdModel;
import com.model.external.oa.OaWorkFlowResult;
import com.model.supply.CorpModel;
import com.model.supply.SupplyBankModel;
import com.model.supply.SupplyInfoModel;
import com.model.supply.SupplyInfoVoModel;
import com.model.supply.SupplyUserModel;
import com.model.sys.SysUser;
import com.service.external.oa.CreateSupplyService;
import com.service.external.oa.GetWFStatusService;
import com.service.external.sap.EntService;

/**
 * 供应商管理
 */

@Service
public class InfoService {

	static final Logger logger = LoggerFactory.getLogger(InfoService.class);

	@Autowired
	InfoMapper infoMapper;
	@Autowired
	SupplyBankDao bankDao;
	@Autowired
	EntService entService;
	@Autowired
	CreateSupplyService createSupplyService;
	@Autowired
	CorpDao corpDao;
	@Autowired
	private RedisUtils redisUtils;
	@Autowired
	UserMapper userDao;
	@Value("${server.url}")
	String baseUrl;

	public HttpResult resetPwd(String loginname) {
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("userAccount", loginname);
		List<SupplyUserModel> models = userDao.selectList(hashMap);
		if (models.size() == 0) {
			return HttpResult.error("用户名不存在");
		}

		try {
			models.get(0).setUserPwd(DesUtils.encrypt(Global.YES + ""));
		} catch (Exception e) {
			logger.error(e.getMessage());
		}

		int result = userDao.update(models.get(0));
		HttpResult httpResult = new HttpResult();
		if (result > 0) {
			httpResult.setMsg("密码重置为1，请重新登录系统！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("重置失败！");
		}
		return httpResult;
	}

	public HttpResult sendMail(String loginname) {
		if (StringUtils.isNullOrEmpty(loginname)) {
			return HttpResult.error("参数不能为空");
		}
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("userAccount", loginname);
		List<SupplyUserModel> models = userDao.selectList(hashMap);
		if (models.size() == 0) {
			return HttpResult.error("用户名不存在");
		}

		HashMap<String, Object> infoHashMap = new HashMap<String, Object>();
		infoHashMap.put("infId", models.get(0).getInfId());
		List<SupplyInfoModel> infoModels = infoMapper.selectList(infoHashMap);
		if (infoModels.size() == 0) {
			return HttpResult.error("供应商不存在");
		}
		String mailString = infoModels.get(0).getInfMail();
		if (StringUtils.isNullOrEmpty(mailString)) {
			return HttpResult.error("邮箱不存在!");
		}
		String tokenString = loginname + "," + System.currentTimeMillis() + "," + UserTypeEnum.SupplyUser.getValue();
		try {
			String destokenString = DesUtils.encrypt(tokenString, DesUtils.getKey());
			String urlString = baseUrl + SpringMvcUtils.getContext() + "/api/supply/resetPwd?loginName=" + loginname
					+ "&token=" + URLEncoder.encode(destokenString, "utf-8");
			if (MailStmpSend.sendHtmlMail(mailString, urlString)) {
				redisUtils.set(Global.REDIS_USER_PREFIX + UserTypeEnum.SupplyUser.getValue() + "-" + loginname,
						models.get(0), Global.PC_BACKGROUND_TOKEN_EXPIRE);
				return HttpResult.ok("已发送至邮箱:" + mailString);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error(e.getMessage());
			return HttpResult.error(e.getMessage());
		}
		return HttpResult.ok("发送失败");
	}

	public HttpResult selectSupplyList(Map<String, Object> queryMap) {
		HttpResult httpResult = new HttpResult();
		EasyuiUtils.addPageNum(queryMap);
		EasyuiUtils.addFilter(queryMap);
		List<SupplyInfoModel> list = infoMapper.selectList(queryMap);
		int count = infoMapper.selectListCount(queryMap);
		httpResult.setRows(list);
		httpResult.setTotal(count);
		logger.info("selectSupplyList:{}", list);

		return httpResult;
	}

	public List selectSupplyForCombo(Map<String, Object> queryMap) {
		EasyuiUtils.addPageNum(queryMap);
		EasyuiUtils.addFilter(queryMap);
		List<SupplyInfoModel> list = infoMapper.selectList(queryMap);
		return list;
	}

	/**
	 * 详情
	 * 
	 * @param
	 * @return
	 */
	public HttpResult selectInfor(String infId) {
		HttpResult httpResult = new HttpResult();
		SupplyInfoVoModel infoModel = infoMapper.selectVO(infId);
		List<SupplyBankModel> bankModels = bankDao.selectByInfId(infId);
		infoModel.setBankModels(bankModels);
		List<CorpModel> corpModels = corpDao.selectByInfId(infId);
		infoModel.setCorpModels(corpModels);
		httpResult.setData(infoModel);
		httpResult.setCode(HttpStatus.SUCCESS_CODE);
		return httpResult;
	}

	@Autowired
	private SysUserMapper sysUserMapper;
	@Autowired
	private LoginMapper loginMapper;

	/**
	 * 保存
	 *
	 * @param
	 * @return
	 */
	@Transactional
	public HttpResult save(SupplyInfoVoModel infoModel) {
		if (infoModel == null) {
			return HttpResult.error("参数不能为空");
		}

		HttpResult httpResult = new HttpResult();
		int result = 0;
		String resIdString = infoModel.getInfId();
		// 主表保存
		if (StringUtils.isNullOrEmpty(resIdString)) {
			infoModel.setInfId(UUID.randomUUID().toString());
		} else {
		}

		// 主表保存
		if (!StringUtils.isNotNull(resIdString)) {
			result = infoMapper.insert(infoModel);
		} else {
			result = infoMapper.update(infoModel);
		}
		if (result > 0) {
			httpResult.setMsg(infoModel.getInfApprovalStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功！");
			httpResult.setData(infoModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(infoModel.getInfApprovalStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败！");
		}
		return httpResult;
	}

	/**
	 * 保存
	 *
	 * @param
	 * @return
	 */
	@Transactional
	public HttpResult commit(SupplyInfoVoModel infoModel) {
		if (infoModel == null) {
			return HttpResult.error("参数不能为空");
		}

		HttpResult httpResult = new HttpResult();
		int result = 0;

		infoModel.setInfApprovalStatus(Global.YES + "");

		if (StringUtils.isNullOrEmpty(infoModel.getInfCode())) {
			HashMap<String, Object> hashMapSupply = new HashMap<>();
			hashMapSupply.put("infId", infoModel.getInfId());
			hashMapSupply.put("registerSupplierName", infoModel.getInfName());
			// 校验企业是否已被注册
			List<SupplyInfoModel> supplyBaseInfo = loginMapper.querySupplyByName(hashMapSupply);
			if (supplyBaseInfo.size() > 0) {
				return HttpResult.error("该企业已注册！");
			}
		}

		HashMap<String, Object> hashMapSupply = new HashMap<>();
		hashMapSupply.put("infId", infoModel.getInfId());
		hashMapSupply.put("infCreditCode", infoModel.getInfCreditCode());
		List<SupplyInfoModel> supplyBaseInfo = loginMapper.querySupplyByName(hashMapSupply);
		if (supplyBaseInfo.size() > 0) {
//			return HttpResult.error("该信用代码已注册！");
		}

		HashMap<String, Object> hashMap = new HashMap<>();
		hashMap.put("casid", infoModel.getInfGroupCode());
		SysUser sysUser = sysUserMapper.selectByCasName(hashMap);
		if (sysUser == null || StringUtils.isNullOrEmpty(sysUser.getSap())) {
			return HttpResult.error("该员工内部账号不存在，请和对接人联系");
		}
		infoModel.setInfGroupName(sysUser.getSap());
		infoModel.setStatus(Global.NO + "");
		// 推送oa
		if (StringUtils.isNullOrEmpty(infoModel.getInfCode())) {
			if (infoModel.getOaFlowId() == 0) {
				HttpResult oaResult = createSupplyService.CreateSupply(infoModel, infoModel.getInfGroupCode());
				if (oaResult.getCode() != HttpStatus.SUCCESS_CODE) {
					// 强制手动事务回滚
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return HttpResult.error(oaResult.getMsg());
				}
				OaWorkFlowResult oaWorkFlowResult = (OaWorkFlowResult) oaResult.getData();
				infoModel.setOaFlowId(oaWorkFlowResult.getOaFlowId());
				infoModel.setOaStatus(Global.YES + "");
			} else {
//				HttpResult oaResult = createSupplyService.CreateSupply(infoModel, infoModel.getInfGroupCode());
//				if (oaResult.getCode() != HttpStatus.SUCCESS_CODE) {
//					// 强制手动事务回滚
//					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//					return HttpResult.error(oaResult.getMsg());
//				}
//				OaWorkFlowResult oaWorkFlowResult = (OaWorkFlowResult) oaResult.getData();
//				infoModel.setOaFlowId(oaWorkFlowResult.getOaFlowId());
//				infoModel.setOaStatus(Global.YES + "");
				return HttpResult.error("不可重复提交！如需修改请联系对接人点击'审核不通过'");
			}
		} else {
			// 推送sap
			HttpResult sapHttpResult = entService.addEntToSap(infoModel);
			if (sapHttpResult.getCode() != HttpStatus.SUCCESS_CODE) {
//				 强制手动事务回滚
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
				return HttpResult.error("sap返回：" + sapHttpResult.getMsg());
			} else {
				infoModel.setStatus(Global.YES + "");
			}
		}

		result = infoMapper.update(infoModel);

		if (result > 0)

		{
			httpResult.setMsg(infoModel.getInfApprovalStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功！");
			httpResult.setData(infoModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(infoModel.getInfApprovalStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败！");
		}
		return httpResult;
	}

	@Autowired
	GetWFStatusService wfStatusService;

	/**
	 * 审核不通过
	 * 
	 * @param infoModel
	 * @return
	 */
	public HttpResult checkNo(String infId) {
		SupplyInfoModel infoModel = infoMapper.load(infId);
		SysUser sysUser = SpringMvcUtils.getSysUser();
		if (!sysUser.getSuperadmin().equals(Global.YES + "")) {
			if (!sysUser.getLoginname().equals(infoModel.getInfGroupCode())) {
				return HttpResult.error("非本人账号所属供应商");
			}
		}
		if (StringUtils.isNotNull(infoModel.getOaFlowId() + "")) {
			// oa退回才可撤回
			HttpResult httpResult = wfStatusService.getWorkflowRequestLogs(infoModel.getInfGroupCode(),
					WorkFlowIdModel.saleContractString, infoModel.getOaFlowId() + "");
			if (httpResult.getCode() != HttpStatus.SUCCESS_CODE) {
				return httpResult;
			}
		}
		infoModel.setInfApprovalStatus(Global.NO + "");
		infoModel.setOaStatus(Global.NO + "");
		infoModel.setOaFlowId(Global.NO);
		infoModel.setStatus(Global.NO + "");
		int result = infoMapper.update(infoModel);
		if (result > 0) {
			return HttpResult.ok("修改成功");
		} else {
			return HttpResult.error("修改失败");
		}
	}

	/**
	 * 推送oa
	 * 
	 * @param infoModel
	 * @return
	 */
	public HttpResult pushOa(SupplyInfoVoModel infoModel) {
		SupplyInfoVoModel infoVoModel = infoMapper.selectVO(infoModel.getInfId());
		List<SupplyBankModel> bankModels = bankDao.selectByInfId(infoModel.getInfId());
		infoModel.setBankModels(bankModels);
		List<CorpModel> corpModels = corpDao.selectByInfId(infoModel.getInfId());
		infoModel.setCorpModels(corpModels);
		// 推送oa
		HttpResult oaResult = createSupplyService.CreateSupply(infoVoModel, infoModel.getInfGroupCode());
		if (oaResult.getCode() != HttpStatus.SUCCESS_CODE) {
			return HttpResult.error(oaResult.getMsg());
		}
		OaWorkFlowResult oaWorkFlowResult = (OaWorkFlowResult) oaResult.getData();
		infoModel.setOaFlowId(oaWorkFlowResult.getOaFlowId());
		infoModel.setOaStatus(Global.YES + "");
		infoMapper.update(infoModel);
		return HttpResult.ok("推送成功");
	}

	/**
	 * 推送pushMdg
	 * 
	 * @param infoModel
	 * @return
	 */
	public HttpResult pushMdg(SupplyInfoVoModel infoModel) {
		SupplyInfoVoModel infoVoModel = infoMapper.selectVO(infoModel.getInfId());

		List<SupplyBankModel> bankModels = bankDao.selectByInfId(infoModel.getInfId());
		infoVoModel.setBankModels(bankModels);
		List<CorpModel> corpModels = corpDao.selectByInfId(infoModel.getInfId());
		infoVoModel.setCorpModels(corpModels);
		// 推送sap
		HttpResult sapHttpResult = entService.addEntToSap(infoVoModel);
		if (sapHttpResult.getCode() != HttpStatus.SUCCESS_CODE) {
			return HttpResult.error("sap返回：" + sapHttpResult.getMsg());
		} else {
			infoVoModel.setInfCode(sapHttpResult.getData().toString());
		}
		infoVoModel.setStatus(Global.YES + "");
		infoVoModel.setOaStatus(Global.NUMERICAL_TWO + "");
		infoMapper.update(infoVoModel);
		return HttpResult.ok("推送成功");
	}

	/**
	 * 删除
	 *
	 * @param
	 * @return
	 */
	public HttpResult delete(String infId) {
		if (!StringUtils.isNotNull(infId)) {
			return HttpResult.error("参数不能为空");
		}
		SupplyInfoModel model = infoMapper.load(infId);
		if (!model.getStatus().equals(Global.NO + "")) {
			return HttpResult.error("非待提交状态，不可删除！");
		}
		HttpResult httpResult = new HttpResult();
		int result = infoMapper.delete(infId);
		if (result > 0) {
			httpResult.setMsg("删除成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	/**
	 * 导出
	 * 
	 * @param queryMap
	 * @param response
	 */
	public void export(Map<String, Object> queryMap, HttpServletResponse response) {
		List<SupplyInfoModel> list = infoMapper.selectList(queryMap);
		logger.info("export:{}", list);
		try {
			EasyExcel.write(response.getOutputStream(), SupplyInfoModel.class).sheet("模板").doWrite(list);
		} catch (IOException e) {
			logger.error("导出错误:{}", e.getMessage());
		}

	}
}
